from django.shortcuts import render,redirect
from django.urls import reverse
from django.views.generic import View
from user.models import User,Address
import re
from django.core.mail import send_mail
from dailyfresh import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Seri
from itsdangerous import SignatureExpired
from django.http import HttpResponse
from celery_tasks.task import sendemail
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from utils.mxin import Login_required
from django_redis import get_redis_connection
from goods.models import GoodsSKU
from order.models import *
from django.core.paginator import Paginator
# Create your views here.
class RegisterView(View):
    def get(self,request):
        return render(request,"register.html")
    def post(self,request):
        data=request.POST
        username=data.get('user_name')
        password=data.get("pwd")
        email=data.get("email")
        allow=data.get("allow")
        print([username,password,email])
        if not all([username,password,email]):
            return render(request,"register.html",{'errmsg':"数据不完整"})
        
        if not re.match(r"^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$",email):
            return render(request,"register.html",{'errmsg':"邮箱格式错误"})
        if allow!='on':
            return render(request,"register.html",{'errmsg':"请同意用户协议"})
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # 用户名不存在
            user = None

        if user:
            # 用户名已存在
            return render(request, 'register.html', {'errmsg': '用户名已存在'})
        user=User.objects.create_user(username=username,password=password,email=email)
        user.is_active=0
        user.save()
        serier=Seri(settings.SECRET_KEY,3600)
        info={'confirm':user.id}
        token=serier.dumps(info).decode("utf8")
        sendemail.delay(email,username,token)
        return redirect(reverse("goods:index"))
class active(View):
    def get(self,request,token):
        seri=Seri(settings.SECRET_KEY,3600)
        try:
            data=seri.loads(token)
            a=User.objects.get(id=data['confirm'])
            a.is_active=1
            a.save()
            return redirect(reverse("user:login"))
        except SignatureExpired:
            return HttpResponse("链接过期")
class login_view(View):
    def get(self,request):
        checked=''
        username=''
        print(request.COOKIES)
        if "username" in request.COOKIES:
            username=request.COOKIES.get('username')
            checked="checked"
        return render(request,"login.html",{'username':username,'checked':checked})
    def post(self,request):
        username=request.POST.get("username")
        password=request.POST.get("pwd")
        remember=request.POST.get("remember")
        print(remember)
        if not all([username,password]):
            return render(request,"login.html",{"errmsg":"用户名或密码错误"})
        user=authenticate(username=username,password=password)
        if user:
            if user.is_active:
                login(request,user)
                next_url=request.GET.get("next",reverse("goods:index"))
                response=redirect(next_url)
                if remember=='on':
                    response.set_cookie('username',username,max_age=7*24*3600)
                else:
                    response.delete_cookie('username')
                return response
            else:
                return render(request,"login.html",{"errmsg":"账户未激活"})
        else:
            return render(request,"login.html",{"errmsg":"用户名或密码错误"})

class User_center_info_view(Login_required,View):
    def get(self,request):
        addr=Address.objects.get_default_address(request.user)
        con=get_redis_connection('default')
        history_id='history_{}'.format(request.user.id)
        goods_ids=con.lrange(history_id,0,4)
        goods_list=[]
        for id in goods_ids:
            a=GoodsSKU.objects.get(id=id)
            goods_list.append(a)
        content={'addr':addr,
                 'goods_list':goods_list,
                 }
        return render(request,'user_center_info.html',content)

class User_center_order_view(Login_required,View):
    def get(self,request):
        page=request.GET.get('page')
        print(page)
        orders=OrderInfo.objects.filter(user=request.user).order_by('-create_time')
        
        print(orders)
        if page:
            print("in if")
            try:
                page=int(page)
            except:
                page=1
        else:
            print("in else")
            page=1
        print("跳过了")
        paginator = Paginator(orders, 5)
        num_pages = paginator.num_pages
        if page>num_pages:
            return redirect(reverse("user:order"))
        print(page)
        orders = paginator.page(page)
        for i in orders:
            print(type(i))
        print(orders)
        pages=[]

        page_range=paginator.page_range
        page=(page-1)//5
        pages=page_range[page*5:(page)*5+5]
        
        # if num_pages<5:
        #     pages=range(1,num_pages+1)
        # else:
        #     if num_pages<5:
        #         pages=range(1,6)
        #     elif num_pages-page>=5:
        #         page=page//5
        #         pages=[i for i in range(page*5,(page+1)*5)]
        #     else:
        #         pages=range(num_pages - 4, num_pages + 1)
        print("end")
        return render(request,'user_center_order.html',{'orders':orders,'order_status':OrderInfo.order_status,'pages':pages})
class User_center_site_view(Login_required,View):
    def get(self,request):
        user1=request.user
        addr=Address.objects.get_default_address(user1)
        return render(request,'user_center_site.html',{'addr':addr})
    def post(self,request):
        receiver=request.POST.get("receiver")
        addr=request.POST.get('addr')
        phone=request.POST.get('phone')
        zipcode=request.POST.get('zipcode')
        print([receiver,addr,phone,zipcode])
        if not all([receiver,addr,phone,zipcode]):
            return render(request,'user_center_site.html',{'errmsg':'数据不完整'})
        if not re.match(r"^1(3|4|5|7|8)\d{9}$",phone):
            return render(request,'user_center_site.html',{'errmsg':'手机号格式错误'})
        user1=request.user
        addr_default=Address.objects.get_default_address(user1)
        if addr_default:
            is_default=False
        else:
            is_default=True
        Address.objects.create(user=user1,receiver=receiver,addr=addr,zip_code=zipcode,is_default=is_default,phone=phone)
        return redirect(reverse("user:site"))
class logout_view(View):
    def get(self,request):
        logout(request)
        return redirect(reverse("goods:index"))

